package com.wn32.main.demo10;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DbUtils {
    public static <T> List<T> query(String sql, Class<T> clazz) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mysqldemo", "root", "root");
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet resultSet = ps.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();

            ArrayList<T> list = new ArrayList<>();

            while (resultSet.next()) {
                T t = clazz.newInstance();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i);
                    String columnTypeName = metaData.getColumnTypeName(i);
                    Field field = clazz.getDeclaredField(columnName);
                    field.setAccessible(true);
                    if (columnTypeName.equalsIgnoreCase("int")) {
                        field.set(t, resultSet.getInt(columnName));
                    } else if (columnTypeName.equalsIgnoreCase("varchar")) {
                        field.set(t, resultSet.getString(columnName));
                    } else if (columnTypeName.equalsIgnoreCase("date")) {
                        field.set(t, resultSet.getDate(columnName));
                    }
                }
                list.add(t);
            }
            connection.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    //List<类> =jdbcTemplate.query("sql",类.class)
}

